# -*- coding: utf-8 -*-
from flask import Response,Flask
from flask import request
import json
import sys
import getopt
import random
from PIL import Image,ImageDraw,ImageFont
import calendar
import os
import requests
import logging
import time
reload(sys)
sys.setdefaultencoding('utf-8')

app = Flask(__name__)

@app.route("/black",methods=['GET'])
def black():
    bit=get_calendar()
    return bit[0]
    
@app.route("/red",methods=['GET'])
def red():
    bit=get_calendar()
    return bit[1]
    
@app.route('/login', methods=['POST', 'GET'])
def login():
    error = None
    if request.method == 'POST':
        if valid_login(request.form['username'],
                       request.form['password']):
            return log_the_user_in(request.form['username'])
        else:
            error = 'Invalid username/password'
    # the code below is executed if the request method
    # was GET or the credentials were invalid
    return render_template('login.html', error=error)
    

@app.route('/image', methods=['POST', 'GET'])
def image():
    img = file("pics/newpic.jpg")
    #img = img.resize((400, 300)) 
    #img = img.convert("1")  
    resp = Response(img, mimetype="image/jpeg")
    return resp

def mono_genmatrix(image, flip, scan_dir, endian, color_reverse):
    width = image.size[0]
    height = image.size[1]
    print(width,height)
    if flip == 'X':
        image = image.transpose(Image.FLIP_TOP_BOTTOM)
    elif flip == 'Y':
        image = image.transpose(Image.FLIP_LEFT_RIGHT)

    if scan_dir == 'H':
        scan_direction = 'Horizontal'
    else:
        scan_direction = 'Vertical'

    if endian == 'B':
        byte_reverse = True
    else:
        byte_reverse = False

    if color_reverse == 'true':
        color_reverse = True
    else:
        color_reverse = False

    unalign = 0
    matrix = list()
    
    if scan_direction == 'Horizontal':
        if (width%8) != 0:
            unalign = 1
        for i in range(0, height):
            for j in range(0, (width//8)+unalign):
                v = 0x00
                rs = 8*j
                re = 8*(j+1)
                if re > width:
                    re = width
                for k in range(rs, re):
                    if image.getpixel((k, i)) != 0:
                        if not byte_reverse:
                            v |= (0x01 << (k%8))
                        else:
                            v |= (0x01 << (7-(k%8)))
                if color_reverse:
                    v ^= 0xff
                matrix.append(v)
    elif scan_direction == 'Vertical':
        if (height%8) != 0:
            unalign = 1
        for i in range(0, width):
            for j in range(0, (height//8)+unalign):
                v = 0x00
                rs = 8*j
                re = 8*(j+1)
                if re > height:
                    re = height
                for k in range(rs, re):
                    if image.getpixel((i, k)) != 0:
                        if not byte_reverse:
                            v |= (0x01 << k%8)
                        else:
                            v |= (0x01 << (7-k%8))
                if color_reverse:
                    v ^= 0xff
                matrix.append(v)
    return matrix

def show_matrix(matrix):
    i = 0
    retn=''
    for v in matrix:
        #print('0x%02x, ' % v)
        retn= retn + '%02x' % v
        i += 1
        if i == 16:
            i = 0
            #print()
    return retn

def get_bit(arg):
    bit=list()
    short_opts = 'hO:F:S:E:H:R'
    opts = ['help', 'operation', 'flip' 'scan-dir', 'endian', 'character-height']

    operation       = 'mono'
    flip            = 'false'
    scan_dir        = 'H'
    endian          = 'B'
    char_height     = '16'
    color_reverse   = 'false'

    if operation == 'mono':
        img = Image.open(arg)
        img = img.resize((400, 300)) 
        img = img.convert("1")
        img.save("pics/newpic.jpg")
        matrix = mono_genmatrix(img, flip, scan_dir, endian, color_reverse)
        #print(matrix)
        bit.append(show_matrix(matrix))
        img.close()
    else:
        #
        l = list()
        for c in arg:
            l.append(ord(c))
        #l.sort()
        # 
        c = list()
        for i in l:
            #print(hex(i) + '')
            c.append(unichr(i))
        #print(c)
        arg = c
        for s in arg:
            #print('/* ' + hex(ord(s)) + ' */')
            if ord(s) < 128:
                w = int(char_height)//2
            else:
                w = int(char_height)
            h = int(char_height)
            img = Image.new("1", (w,h), (1))
            ttfont = ImageFont.truetype("fonts/unifont-13.0.06.ttf", h)
            draw = ImageDraw.Draw(img)
            draw.text((0,0), u'%c' % s, (0), font=ttfont)
            matrix = mono_genmatrix(img, flip, scan_dir, endian, color_reverse)
            bit.append(show_matrix(matrix))
            img.close()
    return bit
    
def get_calendar():
    bit=list()
    short_opts = 'hO:F:S:E:H:R'
    opts = ['help', 'operation', 'flip' 'scan-dir', 'endian', 'character-height']

    operation       = 'mono'
    flip            = 'false'
    scan_dir        = 'H'
    endian          = 'B'
    char_height     = '16'
    color_reverse   = 'false'

    fontPath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'font')
    weatherImgPath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'weatherImg')
    libdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib')
    month = int(time.strftime('%m'))
    year = int(time.strftime('%y'))
    nowDay = int(time.strftime('%d'))
    WEEK = ('星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日')
    MONTH = ('一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一', '十二')

    blackImg = Image.new('1', (400, 300), 255)
    blackDraw = ImageDraw.Draw(blackImg)
    redImg = Image.new('1', (400, 300), 0)
    redDraw = ImageDraw.Draw(redImg)

    width, height = blackImg.size
    # rows = 2 titles + 5 rows of days + 2(head + footer)blank
    # cols = 7 cols of week + 1 blank for left + 3 col for pic
    # rows, cols = 9, len(WEEK) + 4
    rows, cols = 8, len(WEEK) + 2
    colSpace, rowSpace = width // cols, height // rows

    # define font and size
    month_font = os.path.join(fontPath, 'font-old.ttc')
    weather_font = os.path.join(fontPath, 'font-old.ttc')
    week_font = os.path.join(fontPath, 'font-old.ttc')
    day_font = os.path.join(fontPath, 'font-f930.ttc')
    month_size, week_size, day_size, weather_size = 16, 13, 16, 13

    temperature, weather, reportTime, city = getWeather()
    tomorrowWeather, tomorrowNightTemp, tomorrowDayTemp, todayWeather, todayNightTemp, todayDayTemp = getWeatherMore()
    logging.info("reportTime：" + reportTime)
    for i in range(len(WEEK) + 1):
        # draw month title
        if i == 0:
            blackDraw.text((90, 5), u'' + city,
                           fill=0,
                           font=ImageFont.truetype(weather_font, size=weather_size))
            blackDraw.text((90, 20), u'' + temperature + u'°C ',
                           fill=0,
                           font=ImageFont.truetype(weather_font, size=18))
            blackDraw.text((90, 40), u'' + weather,
                           fill=0,
                           font=ImageFont.truetype(weather_font, size=weather_size))
            blackDraw.text((90, 55), u'最高 ' + todayDayTemp + u'|最低 ' + todayNightTemp + u'|更新时间 ' + u'' + reportTime[11:16],
                           fill=0,
                           font=ImageFont.truetype(weather_font, size=weather_size))
            blackDraw.text((colSpace, 30), u' ' + MONTH[month - 1],
                           fill=0,
                           font=ImageFont.truetype(month_font, size=month_size))
            top = rowSpace // 10
            blackDraw.line(xy=[(colSpace, rowSpace * 2 - top * 2 + 5), (colSpace * 8, rowSpace * 2 - top * 2 + 5)],
                           fill=0)
            blackDraw.line(xy=[(colSpace, rowSpace * 2 - top * 1 + 5), (colSpace * 8, rowSpace * 2 - top * 1 + 5)],
                           fill=0)
            continue
        # draw week title
        blackDraw.text((colSpace * i, rowSpace * 2 + 10), u' ' + WEEK[i - 1], fill=0,
                       font=ImageFont.truetype(week_font, size=week_size))

    # draw days
    cal = calendar.Calendar(firstweekday=0)
    row, col = 3, 1
    for day in cal.itermonthdays(year, month):
        if day > 0:
            # if weekday, draw with red color
            if col == 6 or col == 7:
                fill = 255
                redDraw.text((colSpace * col + day_size, rowSpace * row), str(day), fill=fill,
                             font=ImageFont.truetype(day_font, size=day_size))
            else:
                fill = 0
                blackDraw.text((colSpace * col + day_size, rowSpace * row), str(day), fill=fill,
                               font=ImageFont.truetype(day_font, size=day_size))

        # 判断输出日期是否为当天，是则在下面画红色方框标识
        if nowDay == int(day):
            xx = colSpace * col + 11
            yy = rowSpace * row + 22
            size = 30
            redDraw.line(xy=[(xx, yy), (xx + size, yy)], fill=255)
            redDraw.line(xy=[(xx, yy), (xx, yy - size)], fill=255)
            redDraw.line(xy=[(xx, yy - size), (xx + size, yy - size)], fill=255)
            redDraw.line(xy=[(xx + size, yy - size), (xx + size, yy)], fill=255)

        col += 1
        # to a new week
        if col == 8:
            col = 1
            row += 1

    # 添加天气图标
    bmp_name = {u'晴': 'WQING.BMP', u'阴': 'WYIN.BMP', u'多云': 'WDYZQ.BMP',
                u'雷阵雨': 'WLZYU.BMP', u'小雨': 'WXYU.BMP', u'中雨': 'WXYU.BMP'}.get(u'' + weather, None)
    if not bmp_name:
        if u'雨' in weather:
            bmp_name = 'WYU.BMP'
        elif u'雪' in weather:
            bmp_name = 'WXUE.BMP'
        elif u'雹' in weather:
            bmp_name = 'WBBAO.BMP'
        elif u'雾' in weather or u'霾' in weather:
            bmp_name = 'WWU.BMP'
        elif u'阴' in weather:
            bmp_name = 'WYIN.BMP'
    print(weather)
    logging.info("bmp_name:" + bmp_name)
    imgPath = weatherImgPath + r'/' + bmp_name
    logging.info("imgPath:" + imgPath)
    weatherImg = Image.open(imgPath)
    newWeatherImg = weatherImg.resize((40, 40), Image.ANTIALIAS)
    blackImg.paste(newWeatherImg, box=(140, 10))
    #flipBlackImg = blackImg.transpose(Image.FLIP_LEFT_RIGHT)
    #rotateBlackImg = flipBlackImg.rotate(180)
    #blackImg.save("aa.jpg")
    #flipRedImg = redImg.transpose(Image.FLIP_LEFT_RIGHT)
    #rotateRedImg = flipRedImg.rotate(180)
    
    blackImg.resize((400, 300)) 
    blackImg.convert("1")
    matrix = mono_genmatrix(blackImg, flip, scan_dir, endian, color_reverse)
    bit.append(show_matrix(matrix))
    
    redImg.resize((400, 300)) 
    redImg.convert("1")
    matrix2 = mono_genmatrix(redImg, flip, scan_dir, endian, color_reverse)
    bit.append(show_matrix(matrix2))
    
    redImg.close()
    blackImg.close()
    
    return bit

def checkNetwork():
        try:
                requests.get("https://www.baidu.com")
                logging.info("network good")
                return 1
        except:
                logging.info("network bad")
                return 2

def getWeather():
    if checkNetwork() == 1:
        r = requests.get('http://restapi.amap.com/v3/weather/weatherInfo?city=610822&key=64f6fc364b6b427a1b4a4689781b1fa2')
        r.encoding = 'utf-8'
        weatherData = json.loads(r.text)
        w = weatherData['lives'][0]
        temperature = str(w['temperature'])
        weather = str(w['weather'])
        reportTime = str(w['reporttime'])
        city = str(w['city'])
    else:
        temperature = '-1'
        weather = '晴'
        reportTime = '1970-01-01 00:00:00'
        city = '无网络'
    return temperature, weather, reportTime, city


def getWeatherMore():
    tomorrowWeather = "00"
    tomorrowNightTemp = "00"
    tomorrowDayTemp = "00"
    todayWeather = "00"
    todayNightTemp = "00"
    todayDayTemp = "00"
    if checkNetwork() == 2:
        return tomorrowWeather, tomorrowNightTemp, tomorrowDayTemp, todayWeather, todayNightTemp, todayDayTemp
    try:
        r = requests.get(
            'http://restapi.amap.com/v3/weather/weatherInfo?extensions=all&city=610822&key=64f6fc364b6b427a1b4a4689781b1fa2')
        r.encoding = 'utf-8'
        weatherData = json.loads(r.text.encode('utf-8'))
        forecasts = weatherData['forecasts'][0]
        casts = forecasts['casts']
        tomorrowWeather = casts[1]['dayweather']
        tomorrowNightTemp = casts[1]['nighttemp']
        tomorrowDayTemp = casts[1]['daytemp']

        todayWeather = casts[0]['dayweather']
        todayNightTemp = casts[0]['nighttemp']
        todayDayTemp = casts[0]['daytemp']
    except:
        return tomorrowWeather, tomorrowNightTemp, tomorrowDayTemp, todayWeather, todayNightTemp, todayDayTemp
    return tomorrowWeather, tomorrowNightTemp, tomorrowDayTemp, todayWeather, todayNightTemp, todayDayTemp

